﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;


[RequireComponent(typeof(Button))]
public class UGUISwitcher : MonoBehaviour
{
    private Button button;
    [SerializeField]
    private Text switcherText;
    [SerializeField]
    private UGUITweenPosition posTween;//默认动画是从开到关的
    public UnityAction<bool> onValueChange;

    private Color onColor = Color.black; //CommonMethod.HexToColor("14FF00B4");
    private Color offColor = Color.white;

    private bool isOn = true;
    private float m_cachedDuration;

    public bool IsOn
    {
        get { return isOn; }
    }

    public bool interactable
    {
        get { return button.interactable; }
        set { button.interactable = value; }
    }

    private void Awake()
    {
        button = GetComponent<Button>();

        if (null == posTween)
        {
            Debug.Log("posTween不能为空");
            return;
        }
        button.onClick.AddListener(OnSwitchClick);
        posTween.onFinished.Add(new UGUIEventDelegate(this.DisPlayText));
        m_cachedDuration = posTween.duration;
    }

    private void DisPlayText()
    {
        if (null != onValueChange)
        {
            onValueChange.Invoke(isOn);

        }
        //恢复duration
        posTween.duration = m_cachedDuration;
        if (switcherText != null)
        {
            this.switcherText.text = isOn == true ? "<color=#eeffe2>ON</color>" : "<color=#FFF7E2>OFF</color>";
            if (this.GetComponent<Image>() != null)
            {                
                this.GetComponent<Image>().color = isOn ? onColor : offColor;
            }
            else if (button.image!=null)
            {
                button.image.color = isOn ? onColor : offColor;
            }


        }
    }

    public void OnSwitchClick()
    {
        isOn = !isOn;
        posTween.Play(!isOn);
    }
    /// <summary>
    /// 设置switcher不显示动画
    /// </summary>
    /// <param name="isOn"></param>
    public void SetSwithcer(bool isOn)
    {
        this.isOn = isOn;
        posTween.duration = 0.001f;
        posTween.Play(!isOn);
    }
    private void OnDestroy()
    {
        button.onClick.RemoveAllListeners();
        posTween.onFinished.Clear();
    }

}
